package com.md.notes.model.module.permission;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import com.md.notes.model.module.log.LoggerABC;
import com.md.notes.model.module.log.LoggerBuilder;

import java.lang.ref.WeakReference;

public class PermissionModel {
    private static final String[] REQUIRED_PERMISSIONS = {
        /*Manifest.permission.READ_MEDIA_IMAGES,
        Manifest.permission.READ_MEDIA_VIDEO,
        Manifest.permission.READ_MEDIA_AUDIO,*/
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private static final int ANDROID_R = 30; // Android 11
    private static final int ANDROID_Q = 29; // Android 10
    
    private ActivityResultLauncher<String[]> permissionLauncher;
    private ActivityResultLauncher<Intent> manageStorageLauncher;
    private PermissionCallback callback;

    private static final int MSG_OPEN_SETTINGS = 0;
    private static final int MSG_SAVE_MD = 1;
    private WeakReference<Activity> activityRef;

    public interface PermissionCallback {
        void onPermissionResult();
    }

    /**
     * 初始化权限请求器
     * 必须在 Activity 的 onCreate 中调用此方法
     * 
     * @param activity FragmentActivity 实例，用于注册权限请求回调
     * @param callback 权限请求结果的回调接口
     */
    public void init(FragmentActivity activity, PermissionCallback callback) {
        this.callback = callback;

        LoggerABC loggerABC = LoggerBuilder.build(activity);

        if(null == activity){
        }
        // 传统权限请求启动器
        permissionLauncher = activity.registerForActivityResult(
            new ActivityResultContracts.RequestMultiplePermissions(),
            result -> {
                boolean allGranted = true;
                for (Boolean isGranted : result.values()) {
                    if (!isGranted) {
                        allGranted = false;
                        break;
                    }
                }
                if(!allGranted){
                    Message message = mHandler.obtainMessage(MSG_OPEN_SETTINGS);
                    mHandler.sendMessage(message);
                }else{
                    /*Message message = mHandler.obtainMessage(MSG_SAVE_MD);
                    mHandler.sendMessage(message);*/
                }
            }
        );

        // Android 11 存储权限请求启动器
        manageStorageLauncher = activity.registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (android.os.Build.VERSION.SDK_INT >= ANDROID_R) {
                    Message message = mHandler.obtainMessage(MSG_SAVE_MD);
                    mHandler.sendMessage(message);
                }
            }
        );
    }

    /**
     * 检查并请求所需权限
     * 如果已有权限则返回 true，否则发起权限请求并返回 false
     * 权限请求的结果将通过 PermissionCallback 异步返回
     * 
     * @param activity 当前的 Activity 实例
     * @return boolean 是否已经具有所需的全部权限
     */
    public boolean checkAndRequestPermissions(Activity activity) {
        LoggerABC loggerABC = LoggerBuilder.build(activity);
        if (android.os.Build.VERSION.SDK_INT >= 33) {
            if (!Environment.isExternalStorageManager()) {
                try {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                    Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
                    intent.setData(uri);
                    manageStorageLauncher.launch(intent);
                } catch (Exception e) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                    manageStorageLauncher.launch(intent);
                }
                return false;
            }
            // 然后检查媒体权限
            /*String[] mediaPermissions = new String[] {
                    Manifest.permission.READ_MEDIA_IMAGES,
                    Manifest.permission.READ_MEDIA_VIDEO,
                    Manifest.permission.READ_MEDIA_AUDIO
            };

            boolean needRequestMediaPermissions = false;
            for (String permission : mediaPermissions) {
                if (ContextCompat.checkSelfPermission(activity, permission)
                        != PackageManager.PERMISSION_GRANTED) {
                    needRequestMediaPermissions = true;
                    break;
                }
            }

            if (needRequestMediaPermissions) {
                loggerABC.logMessage(LoggerABC.INFO,"请求媒体权限");
                permissionLauncher.launch(mediaPermissions);
                return false;
            }*/
            return true;
        } else if (android.os.Build.VERSION.SDK_INT >= ANDROID_R) {
            if (!Environment.isExternalStorageManager()) {
                try {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                    Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
                    intent.setData(uri);
                    manageStorageLauncher.launch(intent);
                } catch (Exception e) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                    manageStorageLauncher.launch(intent);
                }
                return false;
            }
            return true;
        } else {
            if (hasPermissions(activity)) {
                callback.onPermissionResult();
                return true;
            }
            permissionLauncher.launch(REQUIRED_PERMISSIONS);
            return false;
        }
    }

    /**
     * 检查是否已经获得所有所需权限
     * 
     * @param activity 当前的 Activity 实例
     * @return boolean 是否已经具有所有所需权限
     */
    private boolean hasPermissions(Activity activity) {
        if (android.os.Build.VERSION.SDK_INT >= 33) {
            return Environment.isExternalStorageManager() && hasMediaPermissions(activity);
        } else if (android.os.Build.VERSION.SDK_INT >= ANDROID_R) {
            return Environment.isExternalStorageManager();
        } else {
            return ContextCompat.checkSelfPermission(activity, 
                Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        }
    }

    /**
     * 打开应用设置页面
     */
    private void openAppSettings(Activity activity) {
        Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
        intent.setData(uri);
        try {
            activity.startActivity(intent);
        } catch (Exception e) {
            // 如果跳转失败，打开系统设置页面
            intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
            activity.startActivity(intent);
        }
    }

    // Handler定义为类成员变量
    private final Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG_OPEN_SETTINGS) {
                Activity activity = activityRef.get();
                if (activity != null && !activity.isFinishing()) {
                    openAppSettings(activity);
                }
            }
            if (msg.what == MSG_SAVE_MD) {
                callback.onPermissionResult();
            }
        }
    };

    private boolean hasMediaPermissions(Activity activity) {
        for (String permission : REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(activity, permission) 
                != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
}
